package org.example.sprojcet.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.sprojcet.comment.Valida;
import org.example.sprojcet.entitys.User;
import org.example.sprojcet.entitys.properties.SatokenProperties;
import org.example.sprojcet.mapper.UserMapper;
import org.example.sprojcet.service.UserService;
import org.example.sprojcet.utils.PhoneNumberValidator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final UserMapper userMapper;
    private final SatokenProperties saTokenProperties;

    @PostMapping("login")
    //对应的当我们注册会将密码加密后，与需要将登录逻辑修改一下
    public SaResult login(@RequestBody User loginUser) {
        // 验证手机号格式
        if (!PhoneNumberValidator.isValid(loginUser.getPhone())) {
            return SaResult.error("手机号格式不正确");
        }
        
        //查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, loginUser.getPhone());
        User user = userMapper.selectOne(queryWrapper);
        if(user==null) return SaResult.error("没有此用户");
        
        // 尝试解密数据库中的密码，如果失败则认为是明文密码
        String password;
        try {
            password = SaSecureUtil.aesDecrypt(saTokenProperties.getVerifyKey(), user.getPassword());
        } catch (Exception e) {
            // 解密失败，说明数据库中的密码是明文
            password = user.getPassword();
        }
        
        if(user.getStatus()!=0){
            return SaResult.error("账户处于异常状态");
        }else if(loginUser.getPassword().equals(password)) {
            //登录成功
            StpUtil.login(loginUser.getPhone());
            return  SaResult.data(StpUtil.getTokenInfo());
        }else {
            return SaResult.error("密码错误");
        }
    }

    @PostMapping("logout")
    public SaResult logout(@RequestBody SaResult result) {
        return userService.logout(result);
    }
//得到加密后的密码
    @GetMapping("getEncryptedPassword")
    public SaResult getEncryptedPassword() {
        try {
            String plainPassword = "123456";
            String key = saTokenProperties.getVerifyKey();
            
            if (key == null) {
                return SaResult.error("加密密钥为空");
            }
            
            String encrypted = SaSecureUtil.aesEncrypt(key, plainPassword);
            
            return SaResult.data("加密后的密码: " + encrypted);
        } catch (Exception e) {
            return SaResult.error("加密失败: " + e.getMessage());
        }
    }

    @GetMapping("validatePhone")
    public SaResult validatePhone(@RequestParam String phone) {
        try {
            PhoneNumberValidator.ValidationResult result = PhoneNumberValidator.validateWithDetail(phone);
            return SaResult.data(result);
        } catch (Exception e) {
            return SaResult.error("手机号验证失败: " + e.getMessage());
        }
    }

//    @PostMapping("update")
//    public SaResult update(@Validated(Valida.Update.class)@RequestBody User user) {
//
//    }

    @PostMapping("saveUser")
    public SaResult saveUser(@Validated(Valida.Create.class) @RequestBody User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, user.getPhone());
        User user1 = userMapper.selectOne(wrapper);
        if (user1 != null) {
            return SaResult.error("电话号码已经注册");
        }
        String ciphertext = SaSecureUtil.aesEncrypt(saTokenProperties.getVerifyKey(), user.getPassword());
            user.setPassword(ciphertext);
        return userMapper.insert(user) > 0 ? SaResult.ok("注册成功"):SaResult.error("注册失败");
    }
//    @GetMapping("deleteUser")
//    public SaResult deleteUser(@RequestBody SaResult result) {
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//
//    }

}
